package com.huage_05.download;

import com.huage_05.util.DownLoadUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取资源名及路径
        String filename = request.getParameter("filename");
        String userAgent = request.getHeader("user-agent");
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img/" + filename);

        //设置响应头
        String mimeType = servletContext.getMimeType(filename);
        response.setContentType(mimeType);
        String fileName = DownLoadUtils.getFileName(userAgent, filename);
        response.setHeader("content-disposition","attachment;filename="+fileName);
        //读写文件
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));
        ServletOutputStream sos = response.getOutputStream();
        byte[] bytes=new byte[1024*8];
        int len;
        while ((len=bis.read(bytes))!=-1){
            sos.write(bytes,0,len);
        }
        bis.close();



    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request,response);
    }
}
